#!/bin/bash
# Copyright (c) 2024 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

DEST_DIR_ARG=$1
TMP_DIR_ARG=$2
GENERATOR_ARG=$3

if [[ ! -d $IDLIZE_PATH && "x$IDLIZE_VER" == "x" ]]; then
    echo "Please define IDLIZE_PATH environment that points to idlize source directory."
    echo "Or define IDLIZE_VER environment that points to version in repository."
    lv=`npm view @azanat/idlize dist-tags.latest`
    nv=`npm view @azanat/idlize dist-tags.next`
    echo "Latest version: ${lv} Next version: ${nv}"
    exit 1
fi

if [[ ! -d $IDLIZE_PATH ]]; then
    GENERATOR=${GENERATOR_ARG:=npx --yes @azanat/idlize@$IDLIZE_VER --dts2peer}
else
    # Use the below to run generator from your idlize workspace
    GENERATOR=${GENERATOR_ARG:=node $IDLIZE_PATH/arkgen --idl2peer}
    IDL_INP=$IDLIZE_PATH/runner/out/scraper/out/idl
    if [[ ! -d $IDL_INP ]]; then
        echo "Please generated IDL files in Idlize folder: $IDL_INP"
        exit 1
    fi
    INPUT_FILES=$(find $IDLIZE_PATH/runner/out/scraper/out/idl -type f)
fi

echo "Preprocessing SDK..."

DEST_DIR=${DEST_DIR_ARG:=..}
TMP_DIR=${TMP_DIR_ARG:=./out}
OUT_DIR=${TMP_DIR}

rm -rf ${TMP_DIR}
mkdir -p ${TMP_DIR}

echo "Generating C API from ${IDLIZE_PATH} to ${DEST_DIR} with ${GENERATOR}"

set -e
${GENERATOR} \
    --options-file $IDLIZE_PATH/runner/out/scraper/out/main-config.json \
    --options-file-unittest ace_types.json5 \
    --output-dir ${TMP_DIR} \
    --input-files ${INPUT_FILES} \
    --generator-target e2e-test-dynamic \
    --libace-destination ${OUT_DIR}

# Copy only changed files
rsync -cqr ${OUT_DIR}/unittest/capi/modifiers/generated/e2e/entry/src/main/resources ${DEST_DIR}/entry/src/main
rsync -cqr --delete ${OUT_DIR}/unittest/capi/modifiers/generated/e2e/entry/src/main/ets/fixtures ${DEST_DIR}/entry/src/main/ets
rsync -cqr --delete ${OUT_DIR}/unittest/capi/modifiers/generated/e2e/entry/src/main/ets/tests ${DEST_DIR}/entry/src/main/ets
rm -rf ${TMP_DIR}
echo "The generation has been completed"